<script setup lang="ts">
  // import type { UploadProps } from 'element-plus'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { ref, reactive } from 'vue'
  import { Plus } from '@element-plus/icons-vue'
  import type { UploadProps } from 'element-plus'
  import breadCrumb from '@/components/bread_crumb.vue'
  import { bus } from '@/mitt/mitt.js'

  // 导入api
  import {
    bindAccountApi,
    changeNameApi,
    changeSexApi,
    changeEmailApi,
  } from '@/api/userinfo.js'
  import {
    changeCompanyNameApi,
    getCompanyNameApi,
    getAllSwiperApi,
  } from '@/api/setting'
  // 引入仓库
  import { useUserInfoStore } from '@/store/userinfo.js'
  // 导入组件修改密码弹出框
  import change from './components/change_password.vue'
  // 引入editor 富文本编辑器
  import editor from './components/editor.vue'
  // first
  const userinfoStore = useUserInfoStore()
  const item = ref({
    first: '系统设置',
  })

  const activeName = ref('first')

  const imageUrl = ref('')
  // 提交图片的地址接口
  const avatarUrl = 'http://127.0.0.1:3007/user/uploadAvatar'

  const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
  ) => {
    // imageUrl.value = URL.createObjectURL(uploadFile.raw!)
    if (response.status === 0) {
      userinfoStore.changeImageUrl(response.image_url)
      console.log(userinfoStore.userInfo.image_url)
      ElMessage.success('更新头像成功'),
        // 进行一个图片跟账号绑定
        (async () => {
          const res = await bindAccountApi(
            userinfoStore.userInfo.account,
            response.onlyId,
            response.image_url
          )
          console.log(res)
          console.log(userinfoStore.userInfo.account)
        })()
    }
  }

  const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
      ElMessage.error('头像必须是jpg或者png格式')
      return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
      ElMessage.error('头像必修小于2MB')
      return false
    }
    return true
  }

  const AccountDetailDat = ref({
    // 用户账号
    account: '',
    // 用户姓名
    name: '',
    // 用户性别
    sex: '',
    // 用户部门
    department: '',
    // 用户身份
    indentity: '',
    // 用户邮箱
    email: '',
  })
  // 获取修改密码弹出框的实力
  const changePasswordRef = ref()
  // 点击修改密码按钮
  const changePasswordOnclick = () => {
    changePasswordRef.value.open()
  }
  // 保存姓名
  const saveName = async () => {
    const res = await changeNameApi(
      userinfoStore.userInfo.id,
      userinfoStore.userInfo.name
    )
    // console.log(res);
    if (res.data.status === 0) {
      ElMessage.success('名称更新成功')
    } else {
      ElMessage.error('名称更新失败！！！请检查名称必须为中文')
    }
  }
  // 保存性别
  const saveSex = async () => {
    const res = await changeSexApi(
      userinfoStore.userInfo.id,
      userinfoStore.userInfo.sex
    )
    if (res.data.status === 0) {
      ElMessage.success('性别更新成功')
    } else {
      ElMessage.error('性别更新失败！！！请检查重试')
    }
  }
  // 保存email
  const saveEmail = async () => {
    const res = await changeEmailApi(
      userinfoStore.userInfo.id,
      userinfoStore.userInfo.email
    )
    if (res.data.status === 0) {
      ElMessage.success('email更新成功')
    } else {
      ElMessage.error('email更新失败!!!请检查重试')
    }
  }
  // 测试上传头像的data
  // const testdata = ref('swiper1')

  // second
  const editorP = ref()
  const openEdit = (id: number) => {
    bus.emit('editorTitle', id)
    editorP.value.open()
  }

  // 公司名称
  const companyName = ref()
  // 获取公司名称
  const getCompanyName = async () => {
    const res = await getCompanyNameApi()
    companyName.value = res.data.data[0].set_value
  }
  getCompanyName()
  const changeCompanyName = () => {
    ElMessageBox.confirm('你确定要修改公司名称吗?', '', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })
      .then(async () => {
        const res = await changeCompanyNameApi(companyName.value)
        // console.log(res.data);
        if (res.data.status === 0) {
          ElMessage.success(res.data.message)
        } else {
          ElMessage.error('修改失败！！！请重试')
        }
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消了',
        })
      })
  }

  // 首页管理

  // 上传轮播图成功
  const handleSwiperSuccess: UploadProps['onSuccess'] = (response) => {
    returnAllSwiper()
  }
  // 轮播图
  const imageUrlSwiper = ref([])
  // 获取轮播图
  const returnAllSwiper = async () => {
    const res = await getAllSwiperApi()
    const url = res.data.data.map((item) => {
      return item.set_value
    })
    imageUrlSwiper.value = url
  }
  returnAllSwiper()

  const swiperData = [
    'swiper1',
    'swiper2',
    'swiper3',
    'swiper4',
    'swiper5',
    'swiper6',
  ]
</script>

<template>
  <breadCrumb ref="breadCrumb" :item="item"></breadCrumb>
  <div class="common-wrapped">
    <!-- 内容 -->
    <div class="common-content">
      <el-tabs v-model="activeName" class="demo-tabs">
        <el-tab-pane label="账号详情" name="first">
          <!-- 用户头像 -->
          <div class="account-info-wrapped">
            <span>用户头像：</span>
            <div class="account-info-content">
              <!-- action 是上传头像的接口 -->
              <el-upload
                class="avatar-uploader"
                :action="avatarUrl"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img
                  v-if="userinfoStore.userInfo.image_url"
                  :src="userinfoStore.userInfo.image_url"
                  class="avatar"
                  alt="用户头像"
                />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </div>
          </div>
          <!-- 用户账号 -->
          <div class="account-info-wrapped">
            <span>用户账号：</span>
            <div class="account-info-content">
              <el-input
                v-model="userinfoStore.userInfo.account"
                disabled
              ></el-input>
            </div>
          </div>
          <!-- 修改密码 -->
          <div class="account-info-wrapped">
            <span>修改密码：</span>
            <div class="account-info-content">
              <el-button type="primary" @click="changePasswordOnclick"
                >修改密码</el-button
              >
            </div>
          </div>
          <!-- 用户姓名 -->
          <div class="account-info-wrapped">
            <span>用户姓名：</span>
            <div class="account-info-content">
              <el-input v-model="userinfoStore.userInfo.name"></el-input>
            </div>
            <div class="account-save-button">
              <el-button type="primary" @click="saveName"> 保存</el-button>
            </div>
          </div>
          <!-- 用户性别 -->
          <div class="account-info-wrapped">
            <span>用户性别：</span>
            <div class="account-info-content">
              <el-select v-model="userinfoStore.userInfo.sex">
                <el-option label="男" value="男"></el-option>
                <el-option label="女" value="女"></el-option>
              </el-select>
            </div>
            <div class="account-save-button">
              <el-button type="primary" @click="saveSex">保存</el-button>
            </div>
          </div>
          <!-- 用户部门 -->
          <div class="account-info-wrapped">
            <span>用户部门：</span>
            <div class="account-info-content">
              <el-input
                v-model="userinfoStore.userInfo.department"
                disabled
              ></el-input>
            </div>
          </div>
          <!-- 用户身份 -->
          <div class="account-info-wrapped">
            <span>用户身份：</span>
            <div class="account-info-content">
              <el-input
                v-model="userinfoStore.userInfo.indentity"
                disabled
              ></el-input>
            </div>
          </div>
          <!-- 用户邮箱 -->
          <div class="account-info-wrapped">
            <span>用户邮箱：</span>
            <div class="account-info-content">
              <el-input v-model="userinfoStore.userInfo.email"></el-input>
            </div>
            <div class="account-save-button">
              <el-button type="primary" @click="saveEmail">保存</el-button>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="公司信息" name="second">
          <!-- 公司名称 -->
          <div class="account-info-wrapped">
            <span class="companyLabel">公司名称：</span>
            <div class="account-info-content">
              <el-input v-model="companyName"></el-input>
            </div>
            <div class="account-save-button">
              <el-button type="success" @click="changeCompanyName"
                >编辑公司名称</el-button
              >
            </div>
          </div>
          <!-- 公司介绍 -->
          <div class="account-info-wrapped">
            <span class="companyLabel">公司介绍：</span>

            <div class="account-save-button">
              <el-button type="success" @click="openEdit(1)"
                >编辑公司介绍</el-button
              >
            </div>
          </div>
          <!-- 公司架构 -->
          <div class="account-info-wrapped">
            <span class="companyLabel">公司架构：</span>

            <div class="account-save-button">
              <el-button type="success" @click="openEdit(2)"
                >编辑公司架构</el-button
              >
            </div>
          </div>
          <!-- 公司战略 -->
          <div class="account-info-wrapped">
            <span class="companyLabel">公司战略：</span>

            <div class="account-save-button">
              <el-button type="success" @click="openEdit(3)"
                >编辑公司战略</el-button
              >
            </div>
          </div>
          <!-- 公司现任高层 -->
          <div class="account-info-wrapped">
            <span class="companyLabel">公司现任高层：</span>

            <div class="account-save-button">
              <el-button type="success" @click="openEdit(4)"
                >编辑公司现任高层</el-button
              >
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="首页管理" name="third">
          <div class="home-wrapped">
            <!-- 提示 -->
            <div class="tips">
              <span> 提示: 点击图片框进行切换首页轮播图 </span>
            </div>
            <!-- 轮播图 -->
            <div
              class="swiper-wrapped"
              v-for="(item, index) in swiperData"
              :key="index"
            >
              <div class="swiper-name">轮播图{{ index + 1 }}:&nbsp;&nbsp;</div>
              <el-upload
                class="avatar-uploader"
                action="http://127.0.0.1:3007/set/uploadSwiper"
                :show-file-list="false"
                :on-success="handleSwiperSuccess"
                :before-upload="beforeAvatarUpload"
                :data="item"
              >
                <template #trigger>
                  <img
                    v-if="imageUrlSwiper[index]"
                    :src="imageUrlSwiper[index]"
                    class="swiper"
                  />
                  <img src="@/assets/雪碧图.png" alt="" v-else />
                </template>
              </el-upload>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="其他设置" name="fourth">Task</el-tab-pane>
      </el-tabs>
    </div>
  </div>
  <!-- 修改密码弹出框 -->
  <change ref="changePasswordRef"></change>
  <!-- 富文本编辑器 -->
  <editor ref="editorP"></editor>
</template>

<style lang="scss" scoped>
  // 外壳
  .common-wrapped {
    padding: 8px;
    background: #f5f5f5;
    // 计算 减去了头部还有面包屑 + 2X8=16边距
    height: calc(100vh - 101px);

    // 内容
    .common-content {
      padding: 0 10px;
      height: 100%;
      background: #fff;

      // 账号信息外壳
      .account-info-wrapped {
        display: flex;
        align-items: center;
        padding-left: 50px;
        margin-bottom: 15px;
        .companyLabel {
          width: 112px;
        }
        :deep(.avatar-uploader-icon) {
          width: 160px;
          height: 160px;
        }
        // 账号信息内容
        .account-info-content {
          margin-left: 24px;
          margin-right: 16px;
        }

        // 按钮
        .account-save-button {
          margin-left: 16px;
        }
      }

      // 首页管理外壳
      .home-wrapped {
        padding-left: 50px;
        display: flex;
        flex-direction: column;

        // 提示
        .tips {
          display: flex;
          align-items: center;
          margin-bottom: 8px;

          span {
            font-size: 14px;
            color: silver;
          }
        }

        // 轮播图
        .swiper-wrapped {
          display: flex;
          margin-bottom: 16px;

          // 轮播图名字
          .swiper-name {
            font-size: 14px;
            margin-bottom: 24px;
          }

          .swiper {
            width: 220px;
            height: 65px;
          }
        }
      }
    }
  }

  // 其他设置
  .other-set {
    padding-left: 50px;
    font-size: 14px;

    .department-set {
      margin-bottom: 24px;

      span {
        margin-right: 24px;
      }
    }

    .product-set {
      span {
        margin-right: 24px;
      }
    }
  }

  // 标签页
  .demo-tabs > .el-tabs__content {
    padding: 32px;
    color: #6b778c;
    font-size: 32px;
    font-weight: 600;
  }

  // 上传头像
  .avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  // 输入框的长度
  :deep(.el-input) {
    width: 240px;
  }
  //
  :deep(.el-select__wrapper) {
    width: 240px;
  }
</style>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
</style>
